package cn.xorange.commons.core.basic.controller;


import cn.hutool.core.date.DateUtil;
import cn.xorange.commons.utils.filter.SQLFilter;
import cn.xorange.commons.utils.http.ServletUtils;
import com.github.pagehelper.page.PageMethod;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.Objects;

public class BaseController {


    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
        {
            @Override
            public void setAsText(String text)
            {
                setValue(DateUtil.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    public void startPage() {
        Integer pageNum = ServletUtils.getParameterToInt("pageNum");
        Integer pageSize = ServletUtils.getParameterToInt("pageSize");
        String orderBy = ServletUtils.getParameter("orderBy");
        if(Objects.nonNull(orderBy)){
            orderBy = SQLFilter.escapeOrderBySql(orderBy);
        }
        if(Objects.nonNull(pageNum) && Objects.nonNull(pageSize) &&Objects.nonNull(orderBy)){
            PageMethod.startPage(pageNum, pageSize,orderBy);
        }else if (Objects.nonNull(pageNum) && Objects.nonNull(pageSize)) {
            PageMethod.startPage(pageNum, pageSize);
        }
    }

}
